/**
 * 武器选择界面
 */
class WeaponNewSelectUI extends UIBase{
    private btn_back:BaseButton;
    private img_right:eui.Image;
    private img_left:eui.Image;
    private lb_condition:eui.Label;
    private knife:knife;
    private lb_name:eui.Label;
    private img_price:eui.Image;
    private lb_price:eui.Label;
    private scrollView:BaseScrollView
    private weapon_list:eui.List;
    private _listDataArr:eui.ArrayCollection;

    public curSelectItem:WeaponSmallItem;
    public curSelectItemId:number;
    private btn_use:BaseButton;
    // private btn_take:BaseButton;
    private group_price:eui.Group;
    private system:particle.ParticleSystem;
    private curSelectIndex:number=0;
    private curPageData;
    private curWeaponListUI:WeaponListUI;
    //商品列表
    private shop_list;
    private lb_tips:eui.Label;

    private btn_buy:BaseButton;
    private img_bg:eui.Image;
    private img_spt9:eui.Image;
    private isSelf:boolean = false;
    private btn_vedio:BaseButton;//看武器获取视频专用
    private lb_progress:eui.Label;//进度
    private group_condition:eui.Group;
    private invite_num = 0;
    private video_num = 0;

    constructor()
    {
        super('WeaponNewView');
    }

    public addParticle()
    {
        let texture = RES.getRes('leaf_png');
        let config = RES.getRes("leaf_json");
        this.system = new particle.GravityParticleSystem(texture, config);
        this.addChildAt(this.system,1);
        this.system.emitterX = 0;
        this.system.emitterY = 0;
        this.system.start();
    }

    public init()
    {
        super.init(true);
        this.initAnimation();
        this.addParticle();
        this.curSelectIndex = 1;
        // this.setDate();
        WeaponPrase.instance().getWeaponInfo(this.initUI, this);
    }

    public setDate()
    {
        if(TimeUtil.getIsNight())
        {
            this.img_bg.source = 'bg2_png';
            this.img_spt9.source = 'spt9_bg_di_2_png';
        }
        else
        {
            this.img_bg.source = 'bg_jpg';
            this.img_spt9.source = 'spt9_bg_di_png';
        }
    }

    public initUI(parma)
    {
        if(!parma){
            MessageUtil.tips('error');
            return;
        }
        this.shop_list = parma.shopList;
        this.invite_num = parma.invite_num;
        this.video_num = parma.video_num;
        this.weapon_list.itemRenderer = WeaponNewListUI;
        let data = this.getListByIndex(0);
        EffectUtil.instance().flyObj(this.knife, 300, 10);
        this.UpdateUI(data, 0);
    }

    public addEvent()
    {   
        this.btn_back.addTapHandler(this.close, this);
        this.btn_use.addTapHandler(this.UseHandle, this);
        this.btn_buy.addTapHandler(this.buyHandle, this);
        this.btn_vedio.addTapHandler(this.vedioHandle,this);
        this.img_left.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lastPage, this);
        this.img_right.addEventListener(egret.TouchEvent.TOUCH_TAP, this.nextPage, this);
        GameUtil.addEventListener(EventConst.CHANGE_PAGE, this.changeUI, this);
        GameUtil.addEventListener(EventConst.EVENT_SCROLL_COMPLETE, this.ScrollerComplete, this);
    }

    //视频处理
    public vedioHandle()
    {
        let platform = egret.Capabilities.os;
        if(platform == 'Windows PC')
        {
            // this.video_num++;
            // GameUtil.sendCntTOSever('video_num');
            // if(this.video_num >= 5)
            // {
            //     let data = DataJson.item_define[this.curSelectItemId];
            //     if(data)
            //     {
            //         let weapId = data.relatedId;
            //         RoleCache.instance().curHadWeapon.push(weapId+'');
            //         this.curSelectItem.update();
            //     }
            // }
            // MessageUtil.tips('观看视频成功!');
            // this.updateCurItemUI();
            return;
        }
        let self = this;
        this.touchChildren = false;
       
        let Success_call = function()
        {  
            self.touchChildren = true;
            self.video_num++;
            GameUtil.sendCntTOSever('video_num');
            if(self.video_num >= 5)
            {
                let data = DataJson.item_define[self.curSelectItemId];
                if(data)
                {
                    let weapId:number = data.relatedId;
                    RoleCache.instance().curHadWeapon.push(weapId+'');
                    self.curSelectItem.update();
                }
            }
            MessageUtil.tips('观看视频成功!');
            self.updateCurItemUI();
        };
        let Error_call = function()
        {  
            self.touchChildren = true;
            WeChatgGameManager.instance().showModal('系统提示','观看视频才可以获得武器哦',true, '立即观看',call, this)
        };
        let call:Function = function()
        {
            WeChatgGameManager.instance().showVideoAd(GameConst.adList.other_vedio, Success_call, Error_call, this);
        }
        WeChatgGameManager.instance().showVideoAd(GameConst.adList.other_vedio, Success_call, Error_call, this);
    }

    protected buyHandle()
    {
        let data = DataJson.item_define[this.curSelectItemId];
        if(data)
        {
            let weapId = data.relatedId;
            if(weapId)
            {
                if(weapId == GameConst.InviteWeaponId)
                {
                    MessageUtil.tips('邀请好友获得!');
                    return ;
                }
                let weaponData = WeaponTpl.instance().getWeaponDataByWeaponId(weapId);
                let price = weaponData.condition;
                let result = ConditionUtil.instance().judgeConditon(price);
                if(result == 1)
                {
                    MessageUtil.tips('金币不足！');
                    return;
                }
                else if(result == 2)
                {
                    MessageUtil.tips('钻石不足！');
                }
                else if(result == 0)
                {
                    //条件达成处理
                    let data = {
                        id:weapId,
                        itemId:this.curSelectItemId
                    }
                    this.touchChildren = false;
                    WeaponPrase.instance().buyWeapon(data,this.buyWeaponSuccess, this);
                }
            }
        }
        else
        {
            MessageUtil.tips('未知名的错误！');
        }
    }

    protected lastPage()
    {
        this.scrollView.scrollToLast();
    }

    protected nextPage()
    {
        this.scrollView.scrollToNext();
    }

    protected buyWeaponSuccess()
    {
        let item = this.curSelectItem;
        if(item)
        {
            item.update();
            this.touchChildren = true;
            this.btn_buy.visible = false;
            this.btn_use.visible = true;
        }
    }

    public ScrollerComplete(e:BaseEvent)
    {
        let parma = e.param;
        let index = parma['item'];
        if(this.curSelectIndex != 1)
        {
            let comp = this.weapon_list.getElementAt(index) as WeaponListUI;
            if(comp)
            {
                let data = comp.da;
                if(data)
                {
                    this.curPageData = data;
                    this.curWeaponListUI = comp;
                }
            }
        }
        this.changeBtn();
    }

    protected UseHandle()
    {
        let curUseWeaponId = RoleCache.instance().curWeaponId;    
        if(!this.curSelectItemId)return;
        let hadWeapon = RoleCache.instance().curHadWeapon;
        let data = DataJson.item_define[this.curSelectItemId];
        if(data)
        {
            let weapId = data.relatedId;
            if(curUseWeaponId == weapId)
            {
                MessageUtil.tips('使用中');
                return;
            }
            if(!RoleCache.instance().judgeIsHaveWeapon(weapId) && RoleCache.instance().curExperienceWeapon !=  weapId)
            {
                MessageUtil.tips('尚未拥有！');
            }
            else
            {
                let da = {
                    weapon_id:weapId
                }
                WeaponPrase.instance().useWeapon(da, this.close, this);
            }
        }
    }

    protected changeUI(e:BaseEvent)
    {        
        let parma = e.param;
        let index = parma.index;
        this.curSelectIndex = index;
        this.curSelectItem = null;
        let data = this.getListByIndex(index -1);
        this.UpdateUI(data, index-1);
        this.changeBtn();
    }

    public changeBtn()
    {
        let num = this.scrollView.getTotalItemNum();
        let curItem = this.scrollView.getCurItem();
        this.img_left.visible = this.img_right.visible = true;
        if(num == 1)
        {
            this.img_left.visible = this.img_right.visible = false;
        }
        else if(curItem == 0)
        {
            this.img_left.visible = false;
        }
        else if(curItem == num-1)
        {
            this.img_right.visible = false;
        }
    }

    protected getListByIndex(type)
    {
        let Arr = [];
        let arr = [];
        let obj = {
            id:1,
            page:1,
            good_list:"",
            price:"",
            type:weaponType.self
        }
        if(type == 0)
        {
            //自己
            let list = JSON.parse(JSON.stringify(RoleCache.instance().curHadWeapon));
            let curExperienceWeapon = RoleCache.instance().curExperienceWeapon;
            if(curExperienceWeapon && !RoleCache.instance().judgeIsHaveWeapon(curExperienceWeapon))
            {
                list.push(curExperienceWeapon);
            }
            let index = 1;
            for(let k in list)
            {		
                let v = list[k];
                if(arr.length >= 6)
                {
                    let good_list = arr.join(',');
                    let clone = JSON.parse(JSON.stringify(obj));
                    clone.good_list = good_list;
                    Arr.push(clone);
                    arr = [];
                    obj.id++;
                    obj.page++;
                }
                arr.push(v);
                if(parseInt(k)+1 == list.length)
                {
                    let clone = JSON.parse(JSON.stringify(obj));
                    let good_list = arr.join(',');
                    clone.good_list = good_list;
                    Arr.push(clone);
                    arr = [];
                }
            }
        }
        else
        {
            let list = this.shop_list;
            for(let k in list)
            {	
                let v = list[k];
                if(v.type == type)
                {
                    Arr.push(v);
                }
            }
        }
        return Arr;
    }

    protected UpdateUI(list, type)
    {
        if(!this._listDataArr)
        {
            this._listDataArr = new eui.ArrayCollection();
        }
        if(type == weaponType.self)
        {
            this.group_price.visible = false;
            this.group_condition.visible = false;
            this.isSelf = true;
            // this.btn_use.visible = true;
        }
        else
        {
            this.group_price.visible = true;
            this.isSelf = false;
            // this.btn_use.visible = false;
        }

        this._listDataArr.source = list;
        this.weapon_list.dataProvider = this._listDataArr;
        this.scrollView.initUI();
    }

    public updateCurItemUI()
    {
        let item = this.curSelectItem;
        let weaponData = item.getData().weaponData;
        let itemData = item.getData().itemData;
        this.knife.setUI(weaponData);
        this.btn_vedio.visible = false;
        // this.lb_desc.text = itemData.desc;
        this.lb_name.text = itemData.name;
        let property = weaponData.property;
        let life = weaponData.life;
        let isHave = RoleCache.instance().judgeIsHaveWeapon(weaponData.id);
        if(isHave || RoleCache.instance().curExperienceWeapon == weaponData.id)
        {
            this.btn_use.visible = true;
            this.btn_buy.visible = false;
        }
        else
        {
            this.btn_use.visible = false;
            this.btn_buy.visible = true;
        }
        if(weaponData.condition != '' && !this.isSelf)
        {
            let condition = weaponData['condition'];
            let condiitonData = ConditionUtil.instance().parseConditon(condition);
            let type = condiitonData.type;
            let desc = condiitonData.desc;
            let num = condiitonData.num;
            if(type == conditionType.gold || type == conditionType.diamond)
            {
                this.group_price.visible = true;
                // this.lb_condition.visible = false;
                this.group_condition.visible = false;
                
                this.lb_price.text = desc;
                this.img_price.source = condiitonData.icon;
            }
            else
            {
                this.lb_condition.text = desc;
                this.group_price.visible = false;
                this.group_condition.visible = true;
                if(type == conditionType.invite)
                {
                    this.lb_progress.text = `${this.invite_num}/${num}`;
                }
                else if(type == conditionType.total_vedio)
                {
                    this.btn_buy.visible = false;
                    this.lb_progress.text = `${this.video_num}/${num}`;
                    if(this.video_num >= 5)
                    {
                        this.btn_vedio.visible = false;
                        this.btn_use.visible = true;
                    }
                    else
                    {
                        this.btn_vedio.visible = true;
                    }
                }
            }
        }
        this.lb_tips.visible = true;
        let desc = '';
        if(WeaponPropertyType.threeKnife == property && life > 0)
        {
            desc = StringUtil.getSwfLangStrVar('effect_4',[life+'', weaponData.Probability+'']);
        }
        else if(WeaponPropertyType.comeBack == property)
        {
            desc = StringUtil.getSwfLangStrVar('effect_1',[]);
        }
        else if(WeaponPropertyType.life == property || life>0)
        {
            desc = StringUtil.getSwfLangStrVar('effect_2',[life+'']);
        }
        else if(WeaponPropertyType.threeKnife == property)
        {
            desc = StringUtil.getSwfLangStrVar('effect_3',[weaponData.three_shot_probability+'']);
        }
        else if(WeaponPropertyType.more == property)
        {
            desc = StringUtil.getSwfLangStrVar('effect_5',[weaponData.change_percent+'%']);
        }
        else if(WeaponPropertyType.addOrde == property)
        {
            desc = StringUtil.getSwfLangStrVar('effect_6',[weaponData.change_percent+'%']);
        }
        else
        {
            this.lb_tips.visible = false;
        }
        desc = StringUtil.getColorString('特效：',0x8F68E4) + desc;
        this.lb_tips.textFlow = StringUtil.getTextFlow(desc);


    }

    public setSelcet(item:WeaponSmallItem)
    {
        if(this.curSelectItem && this.curSelectItem != item)
        {
            this.curSelectItem.cancelSelectState();
        }
        this.curSelectItem = item;
        this.curSelectItemId = item.getData().itemData.id;
        this.updateCurItemUI();
    }

    public initAnimation()
    {
        this.img_left.alpha = this.img_right.alpha = 0.5;
        this.LREffect(this.img_right, 1);
        this.LREffect(this.img_left, -1);
    }

    public LREffect(obj, dir)
    {
         var onComplete1:Function = function(){
            if(obj != null){
                var onComplete2:Function = function(){
                    egret.Tween.get(obj).to({
                     alpha:0.5,
                     x:obj.x - dir * 20
                },500).call(onComplete1,this);  
                }
                egret.Tween.get(obj).to({
                    alpha:1,
                    x:obj.x + dir * 20
                }, 500).call(onComplete2, this);
            }
        };
        onComplete1();
    }

    protected close()
    {
        this.remove(0);
    }

    public removeEvent()
    {
        this.btn_back.removeTapHandler();
        this.btn_use.removeTapHandler();
        this.btn_buy.removeTapHandler();
        this.btn_vedio.removeTapHandler();
        this.img_left.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.lastPage, this);
        this.img_right.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.nextPage, this);
        GameUtil.removeEventListener(EventConst.CHANGE_PAGE, this.changeUI, this);
        GameUtil.removeEventListener(BaseScrollView.EVENT_SCROLL_COMPLETE, this.ScrollerComplete);
    }

    public clear()
    {
        super.clear();
        this.curSelectItem = null;
        this.weapon_list.dataProvider = null;
        this.weapon_list.itemRenderer = null;
        this._listDataArr = null;
        this.curSelectItemId = null;
        if(this.system.parent)
        this.system.parent.removeChild(this.system);
        this.system.stop();
        this.system = null;
        this.isSelf = null;
        this.invite_num = null;
        this.video_num = null;
    }
}

window['WeaponNewSelectUI'] = WeaponNewSelectUI;